package net.love5z.web.service;

import java.util.ArrayList;
import java.util.List;

import net.love5z.web.common.utils.ObjectPropUtils;
import net.love5z.web.dao.ShortUrlMapper;
import net.love5z.web.dao.dto.ShortUrlDto;
import net.love5z.web.service.bo.PaginationShortUrlListBo;
import net.love5z.web.service.bo.ShortUrlBo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ShortUrlService {

    private static final String code = "0123456789abcdefghijklmnopqrstuvwxyz";

    @Autowired
    private ShortUrlMapper      shortUrlMapper;

    public List<ShortUrlDto> list() {
        return shortUrlMapper.list();
    }

    public PaginationShortUrlListBo listPage(int pageNo, int pageCount) {
        PaginationShortUrlListBo paginationShortUrlListBo = new PaginationShortUrlListBo();

        int pageStart = (pageNo - 1) * pageCount;

        List<ShortUrlDto> _list = shortUrlMapper.listPage(pageStart, pageCount);
        int count = shortUrlMapper.count();

        int totalPages = count / pageCount;
        totalPages += count % pageCount > 0 ? 1 : 0;

        List<ShortUrlBo> list = new ArrayList<ShortUrlBo>();
        ObjectPropUtils.copyCollectionProperties(_list, list, ShortUrlBo.class);

        paginationShortUrlListBo.setList(list);
        paginationShortUrlListBo.setTotalPages(totalPages);

        return paginationShortUrlListBo;
    }

    public ShortUrlBo getByLongUrl(String longUrl) {
        return (ShortUrlBo) ObjectPropUtils.createAndCopyProperties(
            shortUrlMapper.getByLongUrl(longUrl), ShortUrlBo.class);
    }

    public ShortUrlBo getByOpCode(String opCode) {
        return (ShortUrlBo) ObjectPropUtils.createAndCopyProperties(
            shortUrlMapper.getByOpCode(opCode), ShortUrlBo.class);
    }

    public String insertLongUrl(String longUrl) {

        int maxOpNum = shortUrlMapper.getMaxOpNum();

        int opNum = maxOpNum + 1;

        String opCode = getOpCodeByNum(opNum);

        ShortUrlDto newSu = new ShortUrlDto();
        newSu.setAccessTimes(0);
        newSu.setLongUrl(longUrl);
        newSu.setOpNum(opNum);
        newSu.setOpCode(opCode);

        shortUrlMapper.insert(newSu);

        return opCode;
    }

    public void upDataAccessTimesById(long id) {

        shortUrlMapper.upDataAccessTimesById(id);
    }

    private String getOpCodeByNum(int num) {
        StringBuffer opCodeBuffer = new StringBuffer();
        int temp = num;
        while (temp > 0) {
            opCodeBuffer.insert(0, code.charAt(temp % code.length()));
            temp /= code.length();
        }

        return opCodeBuffer.toString();

    }

}
